#include <iostream>
#include <memory>
#include "lib_acl.h"

#include "version.h"
#include "Log.h"
#include "appexitio.h"

#include "business_def.h"
#include "sqlite_record.h"
#include "spaceMgr.h"
#include "udp_io.h"

namespace GlobalVar {
	bool exitFlag = false;
	extern std::string logname;
};
#ifdef WIN32
//server conf
char SVCNAME[128] = "pyfreeRecord";
char SVCDESC[256] =
"\r\n pyfree Technology Ltd \r\n "
"https://gitee.com/pyzxjfree/pyfree-IotEdge \r\n "
"email:py8105@163.com \r\n "
"pyfree-record system service \r\n "
"Service installation success";
#endif // WIN32

#ifdef WIN32
int MyMain(int argc, char* argv[])
#else
int main(int argc, char *argv[])
#endif
{
	#ifdef WIN32
	GlobalVar::logname = std::string(SVCNAME);
	#else
	GlobalVar::logname = "pyfreeRecord";	//最好与安装脚本保持一致,采用服务名
	#endif
	if (!pyfree::LicenseCheck())
	 {
		printf("license is error, please make sure software instance is right first!");
		exit(true);
	}
	pyfree::versionLog();
	pyfree::checkArg(argc,argv);
	std::cout << "app cache data init start!" << std::endl;
	BusinessDef *bdef_ptr = BusinessDef::getInstance();
	CLogger::createInstance()->Log(MsgInfo,"cache data instance is init first!");
	//日志记录删除
	std::auto_ptr<DiskSpaceMgr> DiskSpaceMgr_ptr(NULL);
	DiskSpaceMgr_ptr.reset(new DiskSpaceMgr(bdef_ptr->getDiskSymbol(),bdef_ptr->getFreeSizeLimit()
		,bdef_ptr->getGLogDir(),"log"));
	DiskSpaceMgr_ptr->add(bdef_ptr->getGDataDir(),"db");
	DiskSpaceMgr_ptr->start();
	//udp-io
	std::auto_ptr<UdpIO> udp_ptr(NULL);
	if (1) {
		udp_ptr.reset(new UdpIO(bdef_ptr->getLocalIp(),bdef_ptr->getLocalPort()));
		udp_ptr->start();
		CLogger::createInstance()->Log(MsgInfo,"UdpIO thread is init and start!");
	}else{
		CLogger::createInstance()->Log(MsgInfo, "UdpIO thread is off!");
	}
	//sqlite记录
	std::cout << "record func init start!" << std::endl;
	std::auto_ptr<SqliteRecord> sqlite_record_ptr(NULL);
	if (bdef_ptr->getRecordFunc()) {
		sqlite_record_ptr.reset(new SqliteRecord());
		sqlite_record_ptr->start();
		CLogger::createInstance()->Log(MsgInfo,"record thread is init and start!");
	}else{
		CLogger::createInstance()->Log(MsgInfo, "record thread is off!");
	}
	//
#ifdef WIN32
	if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ctrlhandler, true))
	{
		CLogger::createInstance()->Log(MsgInfo, "install signal handler success!");
	}
	else
	{
		CLogger::createInstance()->Log(MsgInfo, "install signal handler error!");
	}
#else
	SignalHandler * g_exit_handler = NULL;
	g_exit_handler = new SignalHandler();
	g_exit_handler->printf_out();
#endif // WIN32
	while(!GlobalVar::exitFlag){
		sleep(10);
	}
	return 0;
}
